package com.yhp.servlet;

import com.yhp.bean.Student;
import com.yhp.service.StudentService;
import com.yhp.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/Educational/student/addstu")
public class AddServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService service = new StudentServiceImpl();
        //接收参数
        String stuno = req.getParameter("stuno");
        //判断学号是否重复
        String isrepeat = service.isrepeat(stuno);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(isrepeat != null){
            writer.println("<script>alert('学号已存在，请重新输入！');location.href='/Educational/student/getGradeList';</script>");
        }else {

            String stuname = req.getParameter("stuname");
            String gradeid = req.getParameter("gradeid");
            String sex = req.getParameter("sex");
            String email = req.getParameter("email");
            String phone = req.getParameter("phone");
            String registered = req.getParameter("registered");
            String address = req.getParameter("address");
            String politics = req.getParameter("politics");
            String idNumber = req.getParameter("idNumber");
            String profession = req.getParameter("profession");
            String introduction = req.getParameter("introduction");
            //创建student对象
            Student student = new Student();
            student.setStuno(stuno);
            student.setStuname(stuname);
            student.setGid(Integer.parseInt(gradeid));
            student.setSex(Integer.parseInt(sex));
            student.setEmail(email);
            student.setPhone(phone);
            student.setRegistered(registered);
            student.setAddress(address);
            student.setPolitics(politics);
            student.setIdNumber(idNumber);
            student.setProfession(profession);
            student.setIntroduction(introduction);

            //调用service，完成添加
            int add = service.add(student);


            if(add > 0 ){
                //添加成功
                writer.println("<script>alert('添加成功！');location.href='/Educational/student/getList'</script>");
            }else {
                //添加失败
                writer.println("<script>alert('添加失败！');location.href='/Educational/student/getGradeList'</script>");
            }
        }
    }
}
